import unittest
from core.filter.message import HandleMessageFilter
from test import generator

socket_server = generator.create_socket_server()

class User(object):
    def __init__(self, uid, name):
        self.uid = uid
        self.name = name


class SUser(User):
    def __init__(self, uid, name):
        User.__init__(self, uid, name)
        self.sid = uid


session1 = generator.create_session()
session2 = generator.create_session()

class SessionIdIncustomObjTest(unittest.TestCase):
    def setUp(self):
        self.users = [User("1", "a"), User("2", "b")]
        self.susers = [SUser(session1.sid, "a"), SUser(session2.sid, "b")]
        self.mfilter = HandleMessageFilter();

    def test_get_sessions_failure(self):
        self.assertRaises(RuntimeError, self.mfilter.get_sessions, [session1, session2], [self.susers[0]])

    def test_get_sessions(self):
        """
            测试从response中获得需要发送的session
        """
        send_sessions = self.mfilter.get_sessions({session1.sid: session1, session2.sid: session2}, [self.susers[0]])
        self.assertEqual(1, len(send_sessions))
        self.assertEqual(session1, send_sessions[0], "发送session不匹配")

    def test_get_session_id_values_failure(self):
        self.assertRaises(RuntimeError, self.mfilter.get_session_id_values, self.users)
        self.assertRaises(RuntimeError, self.mfilter.get_session_id_values, self.users[0])
        self.assertRaises(RuntimeError, self.mfilter.get_session_id_values, {"id": 1, "name": 2})

    def test_get_session_id_values(self):
        """
            测试从reponse中获得需要发送的session id
        """
        result_ids = self.mfilter.get_session_id_values(self.susers)
        self.assertEqual([session1.sid, session2.sid], result_ids, "返回id不相等")

        result_ids = self.mfilter.get_session_id_values(self.susers[0])
        self.assertEqual([session1.sid], result_ids, "返回id不相等")

        result_ids = self.mfilter.get_session_id_values({"id": 1, "name": 2, "sid": session1.sid})
        self.assertEqual([session1.sid], result_ids, "返回id不相等")

        result_ids = self.mfilter.get_session_id_values(session1.sid)
        self.assertEqual([session1.sid], result_ids, "返回id不相等")